//
//  SEGCommonDoorViewController.m
//  SEGIntelligentHardware
//
//  Created by Clavis on 2019/5/5.
//  Copyright © 2019 Clavis. All rights reserved.
//

#import "SEGCommonDoorViewController.h"
#import "SEGNewMyDoorListModel.h"
#import "SEGCommonAllDoorListViewController.h"
#import "SEGCommonDoorSubView.h"
#import "SEGOpenDoorBussinessManager.h"
#import "SEGKnowOpenDoorViewController.h"
#import "SEGOpenDoorStrategyViewController.h"
//ViewModel
#import <SEGViewModel/SEGDoorListViewModel.h>
#import "SEGDoorPresentAnimation.h"

@interface SEGCommonDoorViewController ()<UIViewControllerTransitioningDelegate>

@property (nonatomic, strong) NSArray<SEGNewMyDoorListModel *> *commonDoorList;
@property (nonatomic, strong) NSArray *doorViewArray;
@property (nonatomic, strong) UILabel *tipLabel;
@property (nonatomic, strong) UIButton *helpButton;
@property (nonatomic, strong) SEGDoorListViewModel *doorListViewModel;

@property (nonatomic, strong) UIView *contentView;
@end

@implementation SEGCommonDoorViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.commonDoorList = [self.doorListViewModel getOldCommonDoor];
    [self setupUI];
    
    [self addSwipeGesture];
    
    // 拉取门禁新数据（只拉取新数据，但是不更新，下次进入常用门页面再更新）
    [[self.doorListViewModel requestNetAllDoorList] subscribeNext:^(id  _Nullable x) {
    }];
    // 每次进入页面都要提交开门记录
    [self.doorListViewModel submitOpenDoorHistory];
}

- (void)setupUI {
    self.navDisplayType = SEGNavigationBarDisplayTypeHide;
    self.view.backgroundColor = [kColor_W colorWithAlphaComponent:0.95];
    
    UIButton *closeButton = ({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_opendoor_close")] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(closeButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        button;
    });
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.bottom.mas_equalTo(-20);
        make.width.height.mas_equalTo(50);
    }];
    
    UIButton *settingButton = ({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"更多" forState:UIControlStateNormal];
        [button setTitleColor:kColor_1 forState:UIControlStateNormal];
        [button setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"luneng_icon_mine_list_setting")] forState:UIControlStateNormal];
        button.titleLabel.font = kFont_13;
        [button addTarget:self action:@selector(moreButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        button.titleEdgeInsets = UIEdgeInsetsMake(0, 4, 0, 0);
        button.imageEdgeInsets = UIEdgeInsetsMake(0, -4, 0, 0);
        [self.view addSubview:button];
        button;
    });
    [settingButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(50);
        make.height.mas_equalTo(50);
        make.bottom.mas_equalTo(-350);
        make.right.mas_equalTo(-10);
    }];
    
    UIView *doorBackView = [[UIView alloc] init];
    [self.view addSubview:doorBackView];
    [doorBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(240);
        make.bottom.mas_equalTo(-90);
    }];
    
    NSMutableArray *tempDoorArray = [NSMutableArray array];
    [self.commonDoorList enumerateObjectsUsingBlock:^(SEGNewMyDoorListModel * _Nonnull doorModel, NSUInteger idx, BOOL * _Nonnull stop) {
        SEGCommonDoorSubView *doorSubView = [[SEGCommonDoorSubView alloc] init];
        CGRect doorFrame = [self getDoorSubViewFrameWithIndex:idx];
        doorSubView.frame = doorFrame;
        [doorSubView updateUIWithModel:doorModel];
        [doorBackView addSubview:doorSubView];
        [tempDoorArray addObject:doorSubView];
        
        WeakSelf;
        doorSubView.clickBlock = ^{
            weakSelf.helpButton.hidden = YES;
            weakSelf.tipLabel.text = @"";
            
            [[SEGOpenDoorBussinessManager shareInstance] openDoorWithDoorModel:doorModel openDoorSuccessCallback:^(SEGNewOpenDoorModel * _Nonnull data) {
                if (weakSelf.completedCallback) {
                    weakSelf.completedCallback(data);
                }
                [weakSelf closeButtonTap:nil];
            } openDoorFailCallback:^(SEGNewOpenDoorModel * _Nonnull data) {
                weakSelf.helpButton.hidden = NO;
                weakSelf.tipLabel.text = kOpenDoorMessage_Failed_Common;
                weakSelf.tipLabel.textColor = kColor_1;
            }];
        };
        
        [UIView animateWithDuration:0.3 delay:0.3+idx*0.05 usingSpringWithDamping:0.6 initialSpringVelocity:0.3 options:UIViewAnimationOptionLayoutSubviews animations:^{
            doorSubView.y -= 240;
        } completion:nil];
    }];
    
    self.doorViewArray = [tempDoorArray copy];
    
    self.helpButton = ({
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        NSMutableAttributedString *text = [[NSMutableAttributedString alloc]initWithString:@"总是失败?"];
        [text yy_setColor:kColor_S3 range:text.yy_rangeOfAll];
        text.yy_underlineStyle = NSUnderlineStyleSingle;
        text.yy_font = kFont_13;
        [button setAttributedTitle:text forState:UIControlStateNormal];
        [button addTarget:self action:@selector(helpButtonTap:) forControlEvents:UIControlEventTouchUpInside];
        button.hidden = YES;
        [self.view addSubview:button];
        button;
    });
    [self.helpButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(doorBackView.mas_top).offset(-30);
        make.centerX.mas_offset(0);
    }];
    
    self.tipLabel = ({
        UILabel *label = [[UILabel alloc] init];
        label.font = kFont_16;
        [self.view addSubview:label];
        label;
    });
    [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.helpButton.mas_top).offset(-10);
        make.centerX.mas_offset(0);
    }];
}

#pragma mark - 手势
- (void)addSwipeGesture {
    UISwipeGestureRecognizer * recognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleSwipeFrom:)];
    [recognizer setDirection:(UISwipeGestureRecognizerDirectionDown)];
    [self.view addGestureRecognizer:recognizer];
}

- (void)handleSwipeFrom:(UISwipeGestureRecognizer *)recognizer{
    if(recognizer.direction == UISwipeGestureRecognizerDirectionDown) {
        [self closeButtonTap:nil];
    }
}


- (CGRect)getDoorSubViewFrameWithIndex:(NSInteger)index {
    CGFloat initialHeight = 240;
    CGFloat doorWidth = floor(LYScreenWidth()/3.0);
    CGFloat doorHeight = 120;
    CGFloat doorRectY = initialHeight + index/3*doorHeight;
    if (self.commonDoorList.count <= 3) {
        doorRectY = doorHeight/2.0 + initialHeight;
    }

    if (self.commonDoorList.count == 1 || (self.commonDoorList.count == 4 && index == 3)) {
        return CGRectMake(doorWidth, doorRectY, doorWidth, doorHeight);
    }
    if ((self.commonDoorList.count == 2 && index == 0) || (self.commonDoorList.count == 5 && index == 3)) {
        return CGRectMake(doorWidth/2.0, doorRectY, doorWidth, doorHeight);
    }
    if ((self.commonDoorList.count == 2 && index == 1) || (self.commonDoorList.count == 5 && index == 4)) {
        return CGRectMake(doorWidth*1.5, doorRectY, doorWidth, doorHeight);
    }
    return CGRectMake((index % 3)*doorWidth, doorRectY, doorWidth, doorHeight);
}

- (void)closeButtonTap:(UIButton *)sender {
    [self.doorViewArray enumerateObjectsUsingBlock:^(UIView * _Nonnull subDoorView, NSUInteger idx, BOOL * _Nonnull stop) {

        [UIView animateWithDuration:0.2 delay:idx*0.05 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            subDoorView.y += 240;
        } completion:^(BOOL finished) {
            
        }];
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.doorViewArray.count*0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.navigationController.transitioningDelegate = self;
        [self.navigationController dismissViewControllerAnimated:YES completion:^{
            if (self.disapperCallback) {
                self.disapperCallback();
            }
        }];
    });
}

- (void)moreButtonTap:(UIButton *)sender {
    SEGCommonAllDoorListViewController *allDoorVC = [[SEGCommonAllDoorListViewController alloc] init];
    allDoorVC.completedCallback = self.completedCallback;
    allDoorVC.disapperCallback = self.disapperCallback;
    [self.navigationController pushViewController:allDoorVC animated:YES];
}

- (void)helpButtonTap:(UIButton *)sender { 
    SEGOpenDoorStrategyViewController *VC = [SEGOpenDoorStrategyViewController new];
    VC.isHideBar=YES;
    [self.navigationController pushViewController:VC animated:YES];
}
#pragma mark - UIViewControllerAnimatedTransitioning

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
    SEGDoorPresentAnimation* animation = [[SEGDoorPresentAnimation alloc] init];
    animation.isPresent = NO;
    return animation;
}

#pragma mark - Getter
- (SEGDoorListViewModel *)doorListViewModel {
    if (!_doorListViewModel) {
        _doorListViewModel = [SEGDoorListViewModel new];
    }
    return _doorListViewModel;
}

@end
